package com.yima.baseproj.module.sys.user;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yima.baseproj.module.sys.role.model.RoleAddOrEditModel;
import com.yima.baseproj.module.sys.user.model.*;
import com.yima.baseproj.module.sys.user.model.SysUserAddParamModel;
import com.yima.baseproj.module.sys.user.model.SysUserEditParamModel;
import com.yima.baseproj.module.sys.user.model.UserProfile;
import com.yima.baseproj.module.sys.user.model.UserSearchAddOrEditModel;
import com.yima.baseproj.module.sys.user.role.SysUserRoleEntity;
import com.yima.baseproj.module.sys.user.role.SysUserRoleService;
import com.yima.baseproj.security.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class SysUserService extends ServiceImpl<SysUserMapper, SysUserEntity> {

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Value("${upload.webBasePath}")
    private String webbasepath;

    public Page<Map> findAllByPage(Page page, UserSearchAddOrEditModel searchModel) {
        return baseMapper.findBySearchVo(page,searchModel);
    }

    public List<Map> findAllByList(UserSearchAddOrEditModel searchModel) {
        List<Map> userList = baseMapper.findBySearchVo(searchModel);
        return userList;
    }


    public SysUserEntity checkSysUserUnique(String loginName) {
        return getOne(Wrappers.<SysUserEntity>query().eq("login_name",loginName));
    }

    public SysUserEntity findByLoginName(String loginName) {
        return getOne(Wrappers.<SysUserEntity>query().eq("login_name",loginName));
    }

    @Transactional(rollbackFor = Exception.class)
    public void add(SysUserAddParamModel paramModel) {
        SysUserEntity userEntity = new SysUserEntity();
        //获取user表对应的用户信息
        userEntity.setSysUserEntity(paramModel);
        //头像处理
        if(StrUtil.isBlank(userEntity.getHeadUrl())){
            userEntity.setHeadUrl(String.format("%s/app/headimg/headimg.png",webbasepath));
        }
        //获取密码的盐
        String salt = BCrypt.gensalt();
        userEntity.setSalt(salt);
        //设置密码
        userEntity.setPassword(BCrypt.hashpw(paramModel.getPassword(),salt));
        //新增用户,user表
        baseMapper.insert(userEntity);
        //在user_role表新增, 插入user_id,role_id
        saveUserRole(userEntity.getId(), paramModel.getRoleId());
    }

    @Transactional(rollbackFor = Exception.class)
    public void edit(SysUserEditParamModel paramModel) {
        SysUserEntity userEntity = baseMapper.selectById(paramModel.getId());
        userEntity.setSysUserEntity(paramModel);
        if(StrUtil.isBlank(userEntity.getHeadUrl())){
            userEntity.setHeadUrl(String.format("%s/sys/headimg/headimg.png",webbasepath));
        }
        //更新user表
        baseMapper.updateById(userEntity);
        //新增/修改 user_role表
        saveUserRole(userEntity.getId(), paramModel.getRoleId());
    }

    private void saveUserRole(String userid, String roleId) {
        sysUserRoleService.delByUserId(userid);
        //判断roleIdList
        if (!Objects.isNull(roleId) && !roleId.isEmpty()) {
            //List<SysUserRoleEntity> roleList = CollectionUtil.newArrayList();
                SysUserRoleEntity sysUserRole = new SysUserRoleEntity();
                sysUserRole.setRoleId(roleId);
                sysUserRole.setUserId(userid);

            sysUserRoleService.save(sysUserRole);
        }
    }


    public boolean hasDeptUser(String deptId) {
        return count(Wrappers.<SysUserEntity>query().eq("dept_id",deptId)) > 0;
    }

    public UserProfile getUserProfile(String userId) {
        return baseMapper.selectProfileById(userId);
    }

    public SysUserSelect getUserById(String userId) {
        return baseMapper.selectUserById(userId);
    }

    @Transactional(rollbackFor = Exception.class)
    public void delByIds(String[] ids) {
        for (String id : ids) {
            //彻底删除
            sysUserRoleService.delByUserId(id);
            //彻底删除
            baseMapper.deleteById(id);
        }
    }


    /**
     * 根据用户id 查询对应的幼儿园id
     * @return
     */
    public int findKgIdByUserId(){
        SysUserEntity user = baseMapper.selectById(SecurityUtil.getUserId());
        if (ObjectUtil.isNotNull(user.getKgId())&&ObjectUtil.isNotEmpty(user.getKgId())){
            return user.getKgId();
        }else {
            //没有对应的kgId, 返回0
            return 0;
        }
    }
}